#include "recordsmanager.h"
#include <QDebug>

RecordsManager::RecordsManager(QObject *parent) : QObject(parent)
{
    loadRecords();
}

void RecordsManager::loadRecords()
{
    QFile file(m_filePath);
    if(file.open(QIODevice::ReadOnly)) {
        QTextStream in(&file);
        while(!in.atEnd()) {
            QString line = in.readLine();
            QStringList parts = line.split(":");
            if(parts.size() == 2) {
                int diff = parts[0].toInt();
                int time = parts[1].toInt();
                m_records[diff] = time;
            }
        }
        file.close();
    }
}

void RecordsManager::saveRecords()
{
    QFile file(m_filePath);
    if(file.open(QIODevice::WriteOnly)) {
        QTextStream out(&file);
        QMapIterator<int, int> i(m_records);
        while (i.hasNext()) {
            i.next();
            out << i.key() << ":" << i.value() << "\n";
        }
        file.close();
    }
}

void RecordsManager::updateRecord(int difficulty, int seconds)
{
    if(!m_records.contains(difficulty) || seconds < m_records[difficulty]) {
        m_records[difficulty] = seconds;
        saveRecords();
        emit recordUpdated(difficulty);
    }
}

QString RecordsManager::getBestTime(int difficulty) const
{
    if(m_records.contains(difficulty)) {
        int seconds = m_records[difficulty];
        return QString("%1:%2")
            .arg(seconds / 60, 2, 10, QLatin1Char('0'))
            .arg(seconds % 60, 2, 10, QLatin1Char('0'));
    }
    return "N/A";
}


void RecordsManager::clearRecords() {
    m_records.clear();    // 清空内存中的记录
    saveRecords();        // 更新文件
    emit recordUpdated(3); // 触发界面刷新（假设3为最低难度）
    emit recordUpdated(4);
    emit recordUpdated(5);
}
